/*
 * @Author: fanjs
 * @Date: 2025-03-12 10:52:34
 * @Description: 任务列表选择
 */
import React, { useEffect, useState, useCallback } from 'react';
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerBody,
  Button,
  DrawerFooter,
  Radio,
  RadioGroup,
  Tooltip,
  addToast,
  cn,
  Chip
} from "@heroui/react";
import { fetchTemplateListApi } from '@/service/api/email'

interface TemplateDrawerEmits {
  template_id: string | null;
  submit: (template_id: string | null) => void;
  isOpen: boolean;
}
export const CustomRadio = ({ data, value }: any) => {

  return (
    <Radio
      classNames={{
        base: cn(
          "w-full bg-content1 m-0",
          "hover:bg-default-50",
          "cursor-pointer rounded-lg p-3 border-1 border-default-200",
          "data-[selected=true]:border-secondary",
        ),
      }}
      color='secondary'
      value={value}
    >
      <div className="w-[340px]">
        <div className='flex items-center mb-1'>
          <span className='text-sm font-semibold text-default-800'>{data.subject}</span>
        </div>
        <div className="text-tiny text-default-400 mb-0.5">
          包含变量：
          {data.variables.map((item: any, index: number) => (
            <Chip key={index} color="secondary" radius="sm" size="sm" className="mr-1 h-5 rounded-[4px]" variant="flat">
              {item}
            </Chip>
          ))}
        </div>
        <div className="text-tiny text-default-400">最近更新：{data.updated_at}</div>
      </div>
    </Radio>
  );
};

const TemplateDrawer: React.FC<TemplateDrawerEmits> = ({ template_id, submit, isOpen }) => {
  const [templateList, setTemplateList] = useState<any[]>([])
  const [selectedTemplate, setSelectedTemplate] = useState<any>('');

  // 提交
  const handleSelect = () => {
    if (!selectedTemplate) return addToast({ title: '先选择一条模板信息' })
    const row = templateList.find((item) => item.id === selectedTemplate)
    submit(row);
  }
  // 关闭
  const handleClose = () => {
    submit(null);
    setSelectedTemplate(null)
  }

  // 展示时获取模板列表
  const fetchTemplateList = useCallback(async () => {
    try {
      const { data }: any = await fetchTemplateListApi()
      setTemplateList(data)
    } catch {
      addToast({ title: '获取模板列表失败!!' })
    }
  }, []);

  useEffect(() => {
    if (!isOpen) return;
    fetchTemplateList();
    if (template_id) setSelectedTemplate(template_id);
  }, [isOpen, template_id, fetchTemplateList]);

  return (
    <>
      <Drawer
        hideCloseButton
        backdrop="blur"
        classNames={{
          backdrop: "z-40",
          base: "data-[placement=right]:sm:m-2 data-[placement=left]:sm:m-2 rounded-medium",
        }}
        className='z-0'
        isOpen={isOpen}
      >
        <DrawerContent>
          <>
            <DrawerHeader className="items-center absolute top-0 inset-x-0 z-50 flex flex-row gap-2 px-2 py-2 border-b border-default-200/50 bg-content1/50 backdrop-saturate-150 backdrop-blur-lg">
              <Tooltip content="收起弹窗">
                <Button
                  isIconOnly
                  className="text-default-600"
                  size="sm"
                  variant="light"
                  onPress={handleClose}
                >
                  <svg
                    fill="none"
                    height="20"
                    stroke="currentColor"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth="2"
                    viewBox="0 0 24 24"
                    width="20"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path d="m13 17 5-5-5-5M6 17l5-5-5-5" />
                  </svg>
                </Button>
              </Tooltip>
              <span className="text-[15px]">
                选择模板
              </span>
            </DrawerHeader>
            <DrawerBody className="pt-16">

              {(!templateList || templateList.length < 1) && (
                <div className="flex flex-col items-center justify-center h-full">
                  <span className="text-default-400">暂无数据</span>
                </div>
              )}

              <RadioGroup
                classNames={{ base: "w-full" }}
                onValueChange={setSelectedTemplate}
                value={selectedTemplate}
              >
                {templateList && templateList.length > 0 && templateList.map((item) => (
                  <CustomRadio
                    data={item}
                    value={item.id}
                  >
                  </CustomRadio>
                ))}
              </RadioGroup>
            </DrawerBody>
            <DrawerFooter className='flex justify-start border-t border-default-100 py-3 px-4 gap-x-3'>
              {templateList && templateList.length > 0 && <Button variant="solid" color="secondary" onPress={handleSelect}>确 定</Button>}
              <Button variant="flat" color="secondary" onPress={handleClose}>取 消</Button>
            </DrawerFooter>
          </>
        </DrawerContent>
      </Drawer>
    </>
  );
}

export default TemplateDrawer;
